<template>
  <div class="login-bk">
    <div class="login-box">
      <h3 class="title">后台登录</h3>
      <el-form
        ref="loginFormRef"
        :model="userLoginState"
        status-icon
        :rules="rules"
        label-width="90px"
      >
        <el-form-item label="账号:" prop="username" >
          <el-input
            style="width: 200px"
            v-model="userLoginState.username"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="密码:" prop="password">
          <el-input
            style="width: 200px"
            v-model="userLoginState.password"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item>
          <el-button :loading="loading" type="primary" @click="submitForm"
            >进入系统</el-button
          >
          <el-button @click="resetForm">重新填写</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, getCurrentInstance, h } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
// import {doUserLogin} from '@/api/userApi'
import useUserStore from "@/store/user"; //导入pinia建立的store

// 对其进行重命名，在下面进行使用
const userStore = useUserStore();
const router = useRouter();

const loading = ref(false);

// 表单的ref引用
const loginFormRef = ref<FormInstance>();
// 表单项数据
const userLoginState = reactive({
  username: "",
  password: "",
});

// 表单项验证
// 此处如果不想写 any ，就自己写类型（在定义验证信息哪里写上所传入的参数的各个类型）
const validateUsername = (rule: any, value: string, callback: any) => {
  // 由于验证信息哪里已经设置了账号填写处，信息不能为空，所以值一定存在
  if (value.includes("z")) {
    callback(new Error("账号不合法"));
  } else {
    callback();
  }
};

// 首先得到 userLoginState 的类型，然后传给 FormRules
const rules = reactive<FormRules<typeof userLoginState>>({
  // 设置验证信息
  username: [
    {
      required: true,
      whitespace: true,
      message: "账号不能为空",
    },
    {
      validator: validateUsername,
    },
  ],
  password: [
    {
      required: true,
      whitespace: true,
      message: "密码不能为空",
    },
  ],
});

// 提交表单
const submitForm = () => {
  if (!loginFormRef.value) return;
  loading.value = true;
  loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 用户登录验证成功，需要请求后端接口
      // 调用userStore中的fetchLoginAction方法，进行异步操作，然后对state中的数据进行修改。
      let code = await userStore.fetchLoginAction(userLoginState);
      // 当code值为0，即网络请求成功时，弹窗提示用户登录成功
      if (code === 0) {
        ElMessage({
          // 设置弹窗的状态，延时时间和显示内容
          type: "success",
          duration: 1500,
          message: h("div", null, [
            h("span", { style: "color:#529b2e" }, "【提示】：用户登录成功"),
          ]),
          // 当弹窗关闭时，进行路由的跳转，使用replace,路由跳转后不会回来
          onClose: () => {
            loading.value = false;
            router.replace("/");
          },
        });
      }
    } else {
      loading.value = false;
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  if (!loginFormRef.value) return;
  loginFormRef.value.resetFields();
};
</script>

<style lang="scss" scoped>
// @import url("./style.scss");
@import url("../style.scss");
</style>
